/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.donkingliang.imageselector;

import com.donkingliang.imageselector.imageloader.UilImageLoader;
import com.donkingliang.imageselector.util.Constant;
import com.flask.colorpicker.cameralibrary.CameraAbility;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridAbility;
import com.lzy.imagepicker.view.CropImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.ListContainer;
import ohos.agp.components.TableLayout;
import ohos.agp.components.TableLayoutManager;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;
import ohos.security.SystemPermission;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;

/**
 * 主界面
 *
 * @author ImageSelector
 * @since 2021-04-19
 */
public class MainAbility extends Ability {
    /**
     * 页面跳转结果吗
     */
    public static final int REQ_PERMISSION_CODE = 1001;
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000f00, "dqh");
    private ArrayList<ImageItem> images = new ArrayList<>();
    private String img = "";
    private int selectType = 0;
    private final List<String> mPermissions =
            new LinkedList<>(
                    Arrays.asList(
                            SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE));
    private ImagePicker imagePicker;
    private ListContainer gridView;

    // 是否需要裁剪
    private boolean isCrop = false;

    /**
     * onStart
     *
     * @param intent intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(this);
        ImageLoader.getInstance().init(config); // UniversalImageLoader初始化
        ImagePicker.setTakePhotoAbility(CameraAbility.class);
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new UilImageLoader()); // 设置图片加载器

        initView();
        initImagePicker();

        findComponentById(ResourceTable.Id_text_multiple_choice).setClickedListener(component -> {
            imagePicker.setMultiMode(true);
            imagePicker.setSelectLimit(1);
            selectType = 1;
            isCrop = false;
            reqPermissions();
        });

        findComponentById(ResourceTable.Id_text_multi_select9).setClickedListener(component -> {
            imagePicker.setMultiMode(true);
            imagePicker.setSelectLimit(Constant.NAN);
            selectType = 1;
            isCrop = false;
            reqPermissions();
        });

        findComponentById(ResourceTable.Id_text_multi_select).setClickedListener(component -> {
            imagePicker.setMultiMode(true);
            imagePicker.setSelectLimit(Constant.THIRDNAN);
            selectType = 1;
            isCrop = false;
            reqPermissions();
        });
        findComponentById(ResourceTable.Id_text_multiple_choice_tailoring).setClickedListener(component -> {
            imagePicker.setMultiMode(true);
            imagePicker.setSelectLimit(1);
            selectType = 1;
            isCrop = true;
            reqPermissions();
        });

        findComponentById(ResourceTable.Id_text_Taking_pictures).setClickedListener(component -> {
            selectType = Constant.FORE;
            isCrop = false;
            reqPermissions();
        });
        findComponentById(ResourceTable.Id_text_Taking_pictures_tailoring).setClickedListener(component -> {
            selectType = Constant.FORE;
            isCrop = true;
            reqPermissions();
        });
    }

    private void reqPermissions() {
        mPermissions.removeIf(perM -> verifySelfPermission(perM) == PERMISSION_GRANTED || !canRequestPermission(perM));
        if (!mPermissions.isEmpty()) {
            requestPermissionsFromUser(
                    mPermissions.toArray(new String[0]), CameraAbility.REQ_PERMISSION_CODE);
        } else {
            if (selectType == 1) {
                choosePic();
            } else if (selectType == Constant.FORE) {
                enterPage();
            }
        }
    }

    /**
     * enterPage
     */
    public void enterPage() {
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(CameraAbility.class.getName())
                .build();
        Intent intentCamera = new Intent();
        intentCamera.setOperation(operation);
        startAbilityForResult(intentCamera, Constant.ONWZORE);
    }

    /**
     * 权限回调
     *
     * @param requestCode requestCode
     * @param ss ss
     * @param grantResults grantResults
     */
    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] ss, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, ss, grantResults);
        if (requestCode != 0) {
            if (selectType == 1) {
                choosePic();
            } else if (selectType == Constant.FORE) {
                enterPage();
            }
            return;
        }
        boolean isHavePermission = false;
        for (int num = 0; num < ss.length; num++) {
            isHavePermission = grantResults[num] == PERMISSION_GRANTED;
        }
        if (isHavePermission) {
            restart();
        }
    }

    private void choosePic() {
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(ImageGridAbility.class.getName())
                .build();
        Intent intent = new Intent();
        intent.setOperation(operation);
        startAbilityForResult(intent, Constant.ONWZORE);
    }

    private void initView() {
        gridView = (ListContainer) findComponentById(ResourceTable.Id_gridview);
        TableLayoutManager tableLayoutManager = new TableLayoutManager();
        tableLayoutManager.setColumnCount(Constant.THIRD);
        gridView.setLayoutManager(tableLayoutManager);
    }

    private void initImagePicker() {
        imagePicker.setShowCamera(true); // 显示拍照按钮
        imagePicker.setCrop(false); // 允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); // 是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.RECTANGLE); // 裁剪框的形状
        imagePicker.setFocusWidth(Constant.SEVENZORE); // 裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(Constant.SEVENZORE); // 裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(Constant.ONEQIAN); // 保存文件的宽度。单位像素
        imagePicker.setOutPutY(Constant.ONEQIAN); // 保存文件的高度。单位像素
    }

    /**
     * 接受回调的值
     *
     * @param requestCode requestCode
     * @param resultCode resultCode
     * @param resultData resultData
     */
    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        try {
            if (resultData == null) {
                return;
            }
            images.clear();
            imagePicker.getImageLoader().clearMemoryCache();
            super.onAbilityResult(requestCode, resultCode, resultData);
            if (resultCode == ImagePicker.REQUEST_CODE_PREVIEW
                    || resultCode == ImagePicker.RESULT_CODE_ITEMS
                    && requestCode == Constant.ONWZORE) {
                images = resultData.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS);
                if (isCrop) {
                    img = images.get(0).uriSchema;
                }
            } else if (resultCode == REQ_PERMISSION_CODE && requestCode == Constant.ONWZORE) { // 拍照回调
                img = resultData.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS);
                if (!isCrop) {
                    ImageItem imageItem = new ImageItem();
                    imageItem.uriSchema = img;
                    images.add(imageItem);
                }
            }

            if (isCrop) {
                cropImg(img);
            }
            MyAdapter adapter = new MyAdapter(images);
            gridView.setItemProvider(adapter);
        } catch (SecurityException e) {
            HiLog.error(LABEL_LOG, "error" + e);
        }
    }

    /**
     * 图片裁剪
     *
     * @param imgPath imgPath
     */
    public void cropImg(String imgPath) {
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(ImageAbility.class.getName())
                .build();
        Intent intent = new Intent();
        intent.setOperation(operation);
        intent.setParam("img", imgPath);
        startAbilityForResult(intent, Constant.ONWZORE);
        isCrop = false;
    }

    /**
     * 适配器
     *
     * @author ImageSelector
     * @since 2021-04-23
     */

    private class MyAdapter extends BaseItemProvider {
        private final List<ImageItem> items;

        MyAdapter(List<ImageItem> imageItems) {
            this.items = imageItems;
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public ImageItem getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
            Image imageView;
            int size = gridView.getWidth() / Constant.THIRD;
            if (component == null) {
                imageView = new Image(MainAbility.this);
                TableLayout.LayoutConfig params = new TableLayout.LayoutConfig(size, size);
                imageView.setLayoutConfig(params);
                imageView.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
                imageView.setPadding(Constant.TEN, Constant.TEN, Constant.TEN, Constant.TEN);
                ShapeElement element = new ShapeElement();
                element.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#F7F7F7")));
                imageView.setBackground(element);
            } else {
                imageView = (Image) component;
            }

            ImageLoader imageLoader = ImageLoader.getInstance(); // 获取单例实例
            // 加载图片，解码为PixelMap，同步返回PixelMap
            PixelMap pixelMap = imageLoader.loadImageSync(getItem(position).uriSchema);
            imageView.setPixelMap(pixelMap);
            return imageView;
        }
    }
}
